/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Servlets;

import Beans.Ciudad;
import Beans.Habitacion;
import Beans.Hotel;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.util.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.LinkedList;
import javax.imageio.ImageIO;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author sistemas
 */
public class ConsultaReserva extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    private Connection con;
    public void init() throws ServletException{
        try{
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            con=DriverManager.getConnection("jdbc:mysql://localhost/Agencia","root","root");
        }
        catch(Exception ex){
            throw new UnavailableException("Error: "+ex.getMessage());
        }
    }
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try{
            String NomCiudad=request.getParameter("NomCiudad");
            SimpleDateFormat formato= new SimpleDateFormat("dd/MM/yyyy");
            String fechaS=request.getParameter("FechaEntrada");
            HttpSession session=request.getSession();
            session.setAttribute("FechaEntrada", fechaS);
            Date fecha1= formato.parse(fechaS);
            fechaS=request.getParameter("FechaSalida");
            session.setAttribute("FechaSalida", fechaS);
            Date fecha2=formato.parse(fechaS);
            int CantHuespedes=Integer.parseInt(request.getParameter("CantHuespedes"));
            session.setAttribute("CantHuespedes", CantHuespedes);
            if(NomCiudad!=null&&fecha1!=null&&fecha2!=null&&CantHuespedes!=0){
                CallableStatement cs=con.prepareCall("{call EstadiasPorCiudad(?,?,?,?)}");
                cs.setString(1, NomCiudad);
                Calendar cal= Calendar.getInstance();
                cal.setTime(fecha1);
                cal.set(Calendar.HOUR_OF_DAY, 0);
                cal.set(Calendar.MINUTE, 0);
                cal.set(Calendar.SECOND, 0);
                cal.set(Calendar.MILLISECOND, 0);
                cs.setDate(2, new java.sql.Date(cal.getTime().getTime()));
                cal.setTime(fecha2);
                cs.setDate(3, new java.sql.Date(cal.getTime().getTime()));
                cs.setInt(4, CantHuespedes);
                ResultSet rs=cs.executeQuery();
                LinkedList<Habitacion> ListaHab=new LinkedList<Habitacion>();
                while(rs.next()){
                    Habitacion h=new Habitacion(rs.getInt("Numero"),rs.getString("Tipo"), rs.getInt("Capacidad"), rs.getDouble("Precio"), null);
                    h.setUnHotel(BuscarHotel(rs.getInt("IdHotel")));
                    ListaHab.add(h);
                }
                RequestDispatcher reqD=request.getRequestDispatcher("MostrarHabitaciones.jsp");
                request.setAttribute("ListaHab", ListaHab);
                reqD.forward(request, response);
            }
        }
        catch(NumberFormatException ex){
            throw new UnavailableException("Error: "+ex.getMessage());
        }
        catch(ParseException ex){
            throw new UnavailableException("Error: "+ex.getMessage());
        }
        catch(SQLException ex){
            throw new UnavailableException("Error: "+ex.getMessage());
        }
            
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
    public Hotel BuscarHotel(int id) throws SQLException, IOException{
        try{
            PreparedStatement ps=con.prepareStatement("SELECT * FROM Hotel WHERE IdHotel="+id);
            ResultSet rs=ps.executeQuery();
            Hotel h=null;
            while(rs.next()){
                     h = new Hotel(rs.getString("Nombre"),rs.getInt("Clasificacion"),null,null);
                     h.setIdHotel(rs.getInt("IdHotel")); 
                     Blob blob=rs.getBlob("Foto");
                     if(blob!=null){
                        byte[] data=blob.getBytes(1, (int)blob.length());
                        h.setUnaFoto(data);
                     }
                     h.setUnaCiudad(BuscarCiudadId(rs.getInt("CodCiudad")));
            }
            return h;
        }
        catch(SQLException ex){
            throw new SQLException("Error: "+ex.getMessage());
        }
    }
    public Ciudad BuscarCiudadId(int id) throws SQLException{
        try{
            PreparedStatement ps=con.prepareStatement("SELECT * FROM Ciudad WHERE CodCiudad="+id);
            ResultSet rs=ps.executeQuery();
            Ciudad c=null;
            if(rs.next()){
                c=new Ciudad(rs.getString("Nombre"), rs.getString("Pais"), rs.getString("IdiomaOf"));
                c.setCodCiudad(rs.getInt("CodCiudad"));
            }
            return c;
        }
        catch(SQLException ex){
            throw ex;
        }
    }
}
